#include "icmpchecker.h"

#include <iostream>
#include <oping.h>

ICMPChecker::ICMPChecker(const std::string &host)
    : m_host(host)
{
}

ICMPChecker::~ICMPChecker()
{
}

bool ICMPChecker::check()
{
    std::cout << "Checking icmp " << m_host << std::endl;
    pingobj_t *pingobj = ping_construct();
    if (!pingobj) {
        return false;
    }

    bool result = true;
    do {
        if (ping_host_add(pingobj, m_host.c_str()) < 0) {
            result = false;
            std::cout << "ping_host_add error:" << ping_get_error(pingobj) << std::endl;
            break;
        }
        // 设置超时时间
        double timeout = 1.0;
        ping_setopt(pingobj, PING_OPT_TIMEOUT, (void *)&timeout);

        if (ping_send(pingobj) <= 0) {
            result = false;
            std::cout << "ping_send error:" << ping_get_error(pingobj) << std::endl;
            break;
        }

    } while (false);

    ping_destroy(pingobj);
    return result;
}
